//
//  OwnerDynamicCell.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/18.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit

class OwnerDynamicCell: BaseTableViewCell {
    
    @IBOutlet weak var bottomTextView: UIView!
    @IBOutlet weak var middleBgView: UIView!
    @IBOutlet weak var ontentLabel: UILabel!
    @IBOutlet weak var middleMargin: NSLayoutConstraint!
    @IBOutlet weak var imageBrRight: NSLayoutConstraint!
    @IBOutlet weak var imageBrH: NSLayoutConstraint!
    @IBOutlet weak var imageBrowr: ImageBrowser!
    @IBOutlet weak var pingLunBgView: UIView!
    
    @IBOutlet weak var littltBgView: UIView!
    @IBOutlet weak var lastMargin: NSLayoutConstraint!
    weak var butBtn : WCLShineButton!
    
    var model : BusinessActivityModel?
    
    var index : IndexPath?{
    
        didSet{
        
            if index == nil {
                return
            }
            
            if model!.isDark == true {
                
                butBtn.biuDark()
                
            } else {
                
                butBtn.biuLinght()

            }
            
           let hehelabel = pingLunBgView.subviews.first as! UILabel
            
            if model!.like != nil {
                
                hehelabel.attributedText = attributedString3()

            } else {
                hehelabel.attributedText = nil

            }
            
            
            for (idex,item) in pingLunBgView.subviews.enumerated() {
                let temp = item as! UILabel
                
                if idex == 0 {
                    continue
                }
                
                
                temp.text = nil
                
                if idex <= index!.row {
                    
                    if idex % 2 == 0 {
                        
                        temp.attributedText = attributedString2(str: "明天会更好:测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面...\(idex)", font: UIFont.systemFont(ofSize: 14))

                    } else {
                        
                        temp.attributedText = attributedString2(str: "鸭梨山大 回复 明天会更好:测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面测试评论界面...\(idex)", font: UIFont.systemFont(ofSize: 14))
                        
                    }
                    
                }
            }
            
            
            
            ontentLabel.attributedText = attributedString(str: " 苹果CEO库克称，苹果的手机并不是专门为有钱人打造的。因此，科技博客作者克里斯-马特斯治科（Chris Matyszczyk）决定亲自走访一下普通人，看看他们究竟是如何看待苹果及其新款iPhone X的", font: UIFont.systemFont(ofSize: 15))
            
            var url = URL(string: model!.article_cover)
            
            if index!.row == 0{
                
                url = nil
                
            }
            
            imageBrowr.isHidden = false
            
            
            if url == nil {
                
                imageBrowr.isHidden = true
                
                imageBrH.constant = 0
                
                imageBrowr.thumPicURLs = [URL]()
                
                return
            }
            
            
            
            let layout = imageBrowr.collectionViewLayout as! ImageBrowserFlowLayout
            
            var hehehe : [URL]?
            
            if index!.row == 0 {
                
                hehehe = [url!]
                
            } else if index!.row == 1 {
                
                hehehe = [url!]
                
            }else if index!.row == 2 {
                
                hehehe = [url!,url!]
                
            }else if index!.row == 3 {
                
                hehehe = [url!,url!,url!]
                
            }else if index!.row == 4 {
                
                hehehe = [url!,url!,url!,url!]
                
            }else{
                
                hehehe = [url!,url!,url!,url!,url!,url!,url!,url!,url!]
                
            }
            
            
            let (colleSize,itemSize) = layout.calculateSize(thumPicURLs: hehehe!, leftRightMargin: 16)
            
            
            imageBrH.constant = colleSize.height
            
            imageBrRight.constant = colleSize.width
            
            
            
            // 8.3设置cell尺寸
            
            if itemSize !=  CGSize(width: 0, height: 0) {
                
                layout.itemSize = itemSize
                
            }
            
            if index!.row == 0 {
                imageBrowr.thumPicURLs = [url!]
                
            } else if index!.row == 1 {
                imageBrowr.thumPicURLs = [url!]
                
            }else if index!.row == 2 {
                imageBrowr.thumPicURLs = [url!,url!]
                
            }else if index!.row == 3 {
                
                imageBrowr.thumPicURLs = [url!,url!,url!]
                
            }else if index!.row == 4 {
                imageBrowr.thumPicURLs = [url!,url!,url!,url!]
                
            }else{
                imageBrowr.thumPicURLs = [url!,url!,url!,url!,url!,url!,url!,url!,url!]
                
            }
            
            imageBrowr.bigPicURLs = nil
            
            imageBrowr.reloadData()

        }
    }
    

    override func awakeFromNib() {
        super.awakeFromNib()
        contentView.backgroundColor = UIColor.white
        middleMargin.constant = 5
        
        lastMargin.constant = 0
        
//        bottomTextView.addCornerAndBorder(borderColor: UIColor.darkGray, borderWidth: 0.6, masksToBounds: true, cornerRadius: 0)
        
        var param2 = WCLShineParams()
        param2.bigShineColor = UIColor(rgb: (255,95,89))
        param2.smallShineColor = UIColor(rgb: (216,152,148))
        param2.shineCount = 15
        param2.smallShineOffsetAngle = -5
        let bt2 = WCLShineButton(frame: .init(x: 22, y: 11, width: 22, height: 22), params: param2)
        butBtn = bt2
        bt2.fillColor = UIColor(rgb: (255,95,89))
        bt2.color = UIColor(rgb: (170,170,170))
        bt2.image = .like
        bt2.addTarget(self, action: #selector(actions), for: .touchUpInside)
        littltBgView.addSubview(bt2)
        
        
    }
    
    
    func actions() {
        model!.isDark = !(model!.isDark)
        
        if model!.isDark == false {
            
            model?.like = " 鸭梨山大"
            
        } else {
            
            model?.like = nil

        }
        
        
        let temp = viewController() as! BaseViewController
        
        temp.plainTableView.reloadData()
    }

    

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
    }
    
    
    @IBAction func btnDidTap(_ sender: UIButton) {
        
        let temp = viewController() as! OwnerDynamicVC
        
        let textField =  temp.sendView.viewWithTag(99) as! UITextField
        
        temp.didTapBtn = sender
        
        textField.becomeFirstResponder()
        
    }
    
    
    func attributedString(str: String, font: UIFont) -> NSAttributedString? {
        
        // 根据原有字符串生成属性字符串
        let strM = NSMutableAttributedString(string: str)
        
        strM.addAttribute(NSFontAttributeName, value: font, range:NSMakeRange(0, str.characters.count))
        
        strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range:NSMakeRange(0, str.characters.count) )
        
        let paragr = NSMutableParagraphStyle.init()
        
        paragr.lineSpacing = 3;
        
        paragr.paragraphSpacing = 2;
        
        paragr.firstLineHeadIndent = 20

        
        strM.addAttribute(NSParagraphStyleAttributeName, value: paragr, range: NSMakeRange(0, str.characters.count))
        
        
        return strM
        
    }
    

    
    
    
    func attributedString2(str: String, font: UIFont) -> NSAttributedString? {
        
        let patten1 = regexStr(str: "鸭梨山大")
        
        //编写规则
        let patten2 = regexStr(str: "明天会更好")
        //创建正则表达式对象
        
        
        let patten = patten1 + "|" + patten2
        
        //caseInsensitive  忽略大小写  最常用
        //dotMatchesLineSeparators 允许 . 匹配任意字符，包括回车换行
        let regex = try! NSRegularExpression(pattern: patten, options: NSRegularExpression.Options.caseInsensitive)
        
        //根据规则匹配指定字符串中第一个符合规则的字符串，并且返回一个NSTextCheckingResult
        let res = regex.matches(in: str, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: str.characters.count))
        
        
        // 根据原有字符串生成属性字符串
        let strM = NSMutableAttributedString(string: str)
        
        strM.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, str.characters.count))
        
        strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, str.characters.count))
        
        
        let paragr = NSMutableParagraphStyle.init()
        
        paragr.lineSpacing = 2;
        
        paragr.paragraphSpacing = 1;
        
//        paragr.firstLineHeadIndent = 10

        strM.addAttribute(NSParagraphStyleAttributeName, value: paragr, range: NSMakeRange(0, str.characters.count))
        
        
        for temp in res{
            
            strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.themeColor(), range: temp.range)
            
        }
        
        return strM
        
    }
    
    
    func attributedString3() -> NSAttributedString {
        
        let strM = NSMutableAttributedString()
        
        let attachment = EmoticonAttachment()
        
        attachment.image = UIImage(named: "like")
        
        let height = UIFont.systemFont(ofSize: 12).lineHeight
        
        attachment.bounds = CGRect(x: 0, y: -2, width: height, height: height)
        
        let attrStr = NSAttributedString(attachment: attachment)
        
        strM.append(attrStr)
        
        let strM2 = NSMutableAttributedString(string: model!.like!)
        
        strM.append(strM2)
        
        // 4.重新设置插入表情的文字大小
        strM.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, strM.length))
        
        let paragr = NSMutableParagraphStyle.init()
        
        paragr.lineSpacing = 2;
        
//      paragr.firstLineHeadIndent = 20

        strM.addAttribute(NSParagraphStyleAttributeName, value: paragr, range: NSMakeRange(0, strM.length))

        
        return strM

    }
    
    
    func regexStr(str : String) -> String {
        
        var tempStr = ""
        
        for (index,item) in str.characters.enumerated() {
            
            if index == 0 {
                
                tempStr.append("[")

            } else {

                tempStr.append("][")

            }
            
            tempStr.append(item)
            
        }
        
        tempStr.append("]")
        
        return tempStr
        
    }

    
}
